# src/main.py
"""
RL游戏完整版本 - 包含用户注册登录和训练界面的完整流程
"""

import os
import sys
import signal
import atexit
from typing import Dict, Any

# 添加项目路径
current_dir = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, current_dir)
sys.path.insert(0, os.path.join(current_dir, 'frontend'))
sys.path.insert(0, os.path.join(current_dir, 'backend'))

# 导入组件
try:
    from frontend.login_interface import LoginInterface
    from frontend.unified_interface import UnifiedGameInterface
    from frontend.backend_interface import get_backend_interface, cleanup_backend_interface
    print("成功导入所有界面组件")
except ImportError as e:
    print(f"导入组件失败: {e}")
    print("请确保所有必要的文件都已正确部署")
    sys.exit(1)

class RLGameApplication:
    """完整的RL游戏应用程序"""

    def __init__(self):
        # 应用状态
        self.user_config = {}
        self.backend_interface = None
        self.game_interface = None
        self.running = False

        # 设置信号处理
        self._setup_signal_handlers()

        print("游戏智能体应用程序初始化完成")

    def _setup_signal_handlers(self):
        """设置信号处理器"""
        def signal_handler(signum, frame):
            print(f"接收到信号 {signum}，正在清理...")
            self.shutdown()
            sys.exit(0)

        signal.signal(signal.SIGINT, signal_handler)
        signal.signal(signal.SIGTERM, signal_handler)
        atexit.register(self.shutdown)

    def show_login(self):
        """显示登录界面"""
        print("显示用户登录界面...")

        def on_login_success(user_config: Dict[str, Any]):
            """登录成功回调"""
            self.user_config = user_config
            username = user_config.get('username', 'Unknown')
            login_count = user_config.get('user_data', {}).get('login_count', 1)

            print(f"用户 {username} 登录成功 (第{login_count}次登录)")

            # 启动训练界面
            self.start_training_interface()

        # 创建并运行登录界面
        login_interface = LoginInterface(on_login_success)
        self.user_config = login_interface.run()

        # 检查是否成功登录
        if not self.user_config or not self.user_config.get('username'):
            print("用户取消登录或登录失败")
            return False

        return True

    def start_training_interface(self):
        """启动训练界面"""
        try:
            print("初始化后端接口...")
            self.backend_interface = get_backend_interface()

            print("创建训练界面...")
            self.game_interface = UnifiedGameInterface(self.backend_interface)

            # 设置用户信息
            if self.game_interface:
                username = self.user_config.get('username', 'Unknown')
                user_data = self.user_config.get('user_data', {})
                login_count = user_data.get('login_count', 1)

                welcome_msg = f"欢迎 {username} 使用游戏智能体 (第{login_count}次使用)"
                self.game_interface.add_message(welcome_msg)

                # 显示上次登录时间（如果不是第一次）
                last_login = user_data.get('last_login')
                if last_login and login_count > 1:
                    try:
                        import datetime
                        last_time = datetime.datetime.fromisoformat(last_login)
                        self.game_interface.add_message(f"上次登录: {last_time.strftime('%Y-%m-%d %H:%M:%S')}")
                    except:
                        pass

                # 设置接口连接
                self.game_interface.set_backend_interface(self.backend_interface)

                # 设置监听器
                if hasattr(self.backend_interface, 'add_state_listener'):
                    self.backend_interface.add_state_listener(self._on_state_update)
                if hasattr(self.backend_interface, 'add_message_listener'):
                    self.backend_interface.add_message_listener(self._on_message)

            print("启动训练界面...")
            self.running = True

            # 运行游戏界面
            if self.game_interface:
                self.game_interface.run()

        except Exception as e:
            print(f"启动训练界面失败: {e}")
            import traceback
            traceback.print_exc()
            self.shutdown()

    def _on_state_update(self, state):
        """处理状态更新"""
        if self.game_interface:
            self.game_interface.current_game_state = state

    def _on_message(self, message):
        """处理消息"""
        if self.game_interface:
            self.game_interface.add_message(message)

    def run(self):
        """运行应用程序"""
        print("启动游戏智能体...")
        print("=" * 50)
        print("游戏智能体 v2.1")
        print("支持用户注册登录、精灵动画、完整回放功能")
        print("=" * 50)

        try:
            # 显示登录界面
            if self.show_login():
                # 登录成功，训练界面在回调中启动
                pass
            else:
                print("应用程序退出")

        except KeyboardInterrupt:
            print("用户中断")
        except Exception as e:
            print(f"运行时错误: {e}")
            import traceback
            traceback.print_exc()
        finally:
            self.shutdown()

    def shutdown(self):
        """关闭应用程序"""
        if not self.running:
            return

        print("正在关闭应用程序...")
        self.running = False

        try:
            # 清理后端接口
            cleanup_backend_interface()

            # 记录使用统计
            username = self.user_config.get('username', 'Unknown')
            print(f"感谢 {username} 使用游戏智能体")
            print("应用程序已关闭")

        except Exception as e:
            print(f"关闭时错误: {e}")

def main():
    """主函数"""
    try:
        app = RLGameApplication()
        app.run()
    except Exception as e:
        print(f"启动失败: {e}")
        import traceback
        traceback.print_exc()
        return 1

    return 0

if __name__ == "__main__":
    exit_code = main()
    sys.exit(exit_code)